package com.xsm.ppsecret.util;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;

import com.google.gson.Gson;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseNotifier;
import com.xsm.ppsecret.sql.DBHelper;
import com.xsm.ppsecret.ui.ease.ChatListActivity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Author: Xiasem
 * Email: xiasem@163.com
 * Date: 17-2-28.
 */

public class EaseHelper implements EMMessageListener {

    private static EaseHelper instance = null;
    private Context appContext;
    private EaseUI easeUI;
    private SQLiteDatabase dataBase;
    private PreferenceManager mManager;

    public synchronized static EaseHelper getInstance() {
        if (instance == null) {
            instance = new EaseHelper();
        }
        return instance;
    }

    public void init(Context context) {
        appContext = context;
        EMOptions emOptions = new EMOptions();
        emOptions.setAcceptInvitationAlways(true);
        DBHelper dbHelper = new DBHelper(appContext);
        dataBase = dbHelper.getWritableDatabase();
        if (EaseUI.getInstance().init(context, emOptions)) {
            appContext = context;
            EMClient.getInstance().setDebugMode(true);
            easeUI = EaseUI.getInstance();
//            Log.d(TAG, "init: 初始化中");
            //设置用户的头像和其他属性
            setEaseUIProviders();

            //注册接受新消息监听的广播
            EMClient.getInstance().chatManager().addMessageListener(this);
        }
    }

    private void setEaseUIProviders() {
        //set user avator
        easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
//                return getUserInfo(username);
                return null;
            }
        });

        easeUI.getNotifier().setNotificationInfoProvider(new EaseNotifier.EaseNotificationInfoProvider() {
            @Override
            public String getDisplayedText(EMMessage message) {

                return null;
            }

            @Override
            public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {

                return null;
            }

            @Override
            public String getTitle(EMMessage message) {
                return "您有一条新消息";
            }

            @Override
            public int getSmallIcon(EMMessage message) {
                return 0;
            }

            @Override
            public Intent getLaunchIntent(EMMessage message) {
                String from = message.getFrom();
                String nickName = message.getStringAttribute("nickName", null);
                Intent intent = new Intent(appContext, ChatListActivity.class);
                intent.putExtra("user_id", from);
                intent.putExtra("nickName", nickName);
                return intent;
            }
        });
    }

//    private EaseUser getUserInfo(String username){
//        // To get instance of EaseUser, here we get it from the user list in memory
//        // You'd better cache it if you get it from your server
//        EaseUser user = null;
//        if(username.equals(EMClient.getInstance().getCurrentUser())) {
//            user = new EaseUser(username);
//            String nickName = mManager.getUserInfo().getNickName();
//            if (nickName != null) {
//                user.setNickname(nickName);
//            }
//            String userHeadUrl = mManager.getUserInfo().getHeadPortrait();
//            if (userHeadUrl != null && !userHeadUrl.isEmpty()) {
//                user.setAvatar(userHeadUrl);
//            }
//            return user;
//        } else {
//            DaoEaseUser daoEaseUser = EaseUserSql.queryUser(dataBase, username);
//            if (daoEaseUser.getUsername() != null && !daoEaseUser.getNickname().isEmpty()) {
//                //查找数据库，设置信息给用户
//                user = new EaseUser(username);
//                user.setNickname(daoEaseUser.getNickname());
//                user.setAvatar(daoEaseUser.getHeadimage());
//            } else {
//                user = new EaseUser("");
//                Map map = new HashMap();
//                map.put("userId", username);
//                Gson gson = new Gson();
//                String json = gson.toJson(map);
//                Call<UserDTOWrapper> call = mHttpServer.queryUser(json, "", HttpSetting.getDeviceId(appContext));
//                call.enqueue(this);
//
//            }
//            return user;
//        }
//    }

    public EaseNotifier getNotifier(){
        return easeUI.getNotifier();
    }

    /**
     * 接收新消息监听
     */
    @Override
    public void onMessageReceived(List<EMMessage> list) {
        for (EMMessage emMessage : list) {
            // in background, do not refresh UI, notify it in notification bar
            if(!easeUI.hasForegroundActivies()){
                getNotifier().onNewMsg(emMessage);
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }
}
